<?php

class My_Mem{
    public function get($key, $expired, $memcache = false){
        if(!isset($memcache) || !$memcache){
            $memcache = new Memcache;
            $memcache->connect('localhost',MEMCACHE_PORT) or die ("Could not connect");
        }
        return unserialize($memcache->get($key));
        // Sửa vấn đề làm chậm code
        /*
        $memcache = new Memcache;
        $memcache->connect('localhost',MEMCACHE_PORT) or die ("Could not connect");
        if($memcache->get("listKey_".BASE_URL.'_'.ENV)){
            $listKey = unserialize($memcache->get("listKey_".BASE_URL.'_'.ENV));
        }else{
            $listKey = array();
        }
        if(!in_array($key, $listKey)){
            $listKey[] = $key;
            $memcache->set("listKey_".BASE_URL.'_'.ENV, serialize($listKey), false, $expired);
        }
        return unserialize($memcache->get($key));
        */
    }
    public function set($key, $data, $flag, $expired, $memcache = false, $gameId = null){
        if(!isset($memcache) || !$memcache){
            $memcache = new Memcache;
            $memcache->connect('localhost',MEMCACHE_PORT) or die ("Could not connect");
        }
        if(!isset($gameId) || !$gameId){
            $params             = Zend_Controller_Front::getInstance()->getRequest()->getParams();
            $gameId             = 0;
            if(isset($params['game'])){
                $gameId         = $params['game'];
            }
        }
        
        if($memcache->get($key)){
            $memcache->replace($key, $data, $flag, $expired);
        }else{
            $memcache->set($key, $data, $flag, $expired);
            # luu lai danh sach key trong memcache
            $listKey = unserialize($memcache->get("listKey_".BASE_URL.'_'.ENV.'_'.$gameId));
            $listKey[] = $key;
            $memcache->set("listKey_".BASE_URL.'_'.ENV.'_'.$gameId, serialize($listKey), $flag, $expired);
        }
        // Sửa vấn đề làm chậm code
        /*
        $memcache = new Memcache;
        $memcache->connect('localhost',MEMCACHE_PORT) or die ("Could not connect");
        
        if($memcache->get($key)){
            $memcache->replace($key, $data, $flag, $expired);
        }else{
            $memcache->set($key, $data, $flag, $expired);
        }
        # luu lai danh sach key trong memcache
        if($memcache->get("listKey_".BASE_URL.'_'.ENV)){
            $listKey = unserialize($memcache->get("listKey_".BASE_URL.'_'.ENV));
        }else{
            $listKey = array();
        }
        if(!in_array($key, $listKey)){
            $listKey[] = $key;
            $memcache->set("listKey_".BASE_URL.'_'.ENV, serialize($listKey), $flag, $expired);
        }
        */
    }
}